Class Inheritance

Class Inheritance 

Inheritance is an object oriented concept which is used to reusability of code. You can achieve inheritance by using extends keyword. To achieve inheritance a class must extend to other class. A class which is extended called super or parent class. a class which extends class is called derived or base class. 

class SubClassName extends SuperClassName(){   

 }

 Important terminology

  • Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
  • Sub Class: The class that inherits the other class is known as subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
  • Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
object test {
class Employee{
var salary:Float = 10000
}

class Programmer extends Employee{
var bonus:Int = 5000
println("Salary = "+salary)
println("Bonus = "+bonus)
}

object MainObject{
def main(args:Array[String]){
new Programmer()
}
}
}

Type of inheritance

Below are the different types of inheritance which are supported by Scala.

Single Inheritance: In single inheritance, derived class inherits the features of one base class. In the image below, class A serves as a base class for the derived class B.

 

class Parent
{
var Name: String = "Vinayak"
}

class Child extends Parent
{
var Age: Int = 22

def details()
{
println("Name: " +Name);
println("Age: " +Age);
}
}

object Main
{
def main(args: Array[String])
{
val ob = new Child();
ob.details();
}
}

 

Constructor in Scala

Constructors are mainly used to initialize the object state. This object initializing happens at the time of object creation, and they are called only once.There are two types of constructors in Scala: Primary and Auxiliary.


class Employee {
  var salary: Int = 100

  def getSalary() = salary
  def setSalary(newSalary: Int) = {
    salary = newSalary
  }
}

object Main
{
  // Main method
  def main(args: Array[String])
  {
    // Class object
    var obj = new Employee();
    println(obj.salary);
  }
}

No comments:

Post a Comment